package com.fingard.dsp.bank.directbank.bocom12;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.bocom13.util.Mac;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextWriter;

public class BOCOM12Base extends DirectBase implements ITcpClient {
	protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }
	
	/**
	 * 获取批次序号
	 * 
	 * @param tmpReqDir 当前目录
	 * @param length 固定长度位数
	 * @return 实际批次序号
	 */
	public static String getBatSeqNo(String tmpReqDir, int length) {
		int batSeqNo = 0;
		File tmpFileDir = new File(tmpReqDir);
		if (tmpFileDir.exists()) {
			File[] tmpFileList = tmpFileDir.listFiles();
			if (tmpFileList != null) {
				int i = 0;
				for (File tmpFile : tmpFileList) {
					if (tmpFile.getName().endsWith(".gz")) {
						i++;
					}
				}
				batSeqNo = i + 1;
			} else {
				batSeqNo = 1;
			}
		} else {
			batSeqNo = 1;
		}
		return String.format("%0" + length + "d", batSeqNo);
	}
	
	/**
	 * 拼接联机交易通用报文头
	 * 
	 * @param xmlWriter
	 * @param tmpBankHeader
	 * @throws Exception
	 */
	protected void writeCommonHeader(XmlTextWriter xmlWriter,BOCOM12Header tmpBankHeader) throws Exception {
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
		xmlWriter.writeStartElement("Req");
		
		xmlWriter.writeStartElement("Head");
		xmlWriter.writeElementString("TrCode", tmpBankHeader.transCode);/* 交易码:参见《交通银行资金清算平台数据字典》2.1交易码 */
		
		xmlWriter.writeStartElement("Sender");/* 交易请求方 */
		xmlWriter.writeElementString("OrgType", "I");/* 机构类型 */
		xmlWriter.writeElementString("OrgId", bankFront.corpNo);/* 机构ID */
		xmlWriter.writeElementString("BrchId", "");/* 交易区域(保险分公司编码) */
		xmlWriter.writeElementString("SubBrchId", "");/* 交易机构 */
		xmlWriter.writeElementString("TermId", "");/* 交易终端号 */
		xmlWriter.writeElementString("TrOper", "");/* 交易柜员号(保险方柜员代码) */
		xmlWriter.writeElementString("TrOperName", "");/* 交易柜员名称(保险方柜员名称) */
		xmlWriter.writeElementString("ChanNo", "93");/* 交易渠道(固定填写"93") */
		xmlWriter.writeElementString("OriBusDate", "");/* 原业务日期 */
		xmlWriter.writeElementString("OriSeqNo", "");/* 原交易流水号 */
		xmlWriter.writeElementString("BusDate", Format.Date8Format.format(new Date()));/* 业务日期 */
		xmlWriter.writeElementString("SeqNo", tmpBankHeader.reqSeqID);/* 交易流水号 */
		xmlWriter.writeElementString("TrDate", Format.Date8Format.format(new Date()));/* 交易日期 */
		xmlWriter.writeElementString("TrTime", Format.Time6Format.format(new Date()));/* 交易时间 */
		xmlWriter.writeEndElement();
		
		xmlWriter.writeStartElement("Recver");/* 交易应答方 */
		xmlWriter.writeElementString("OrgType", "B");/* 机构类型 */
		xmlWriter.writeElementString("OrgId", "3012900");/* 机构ID(3012900:交通银行) */
		xmlWriter.writeElementString("BrchId", "");/* 交易区域(银行分行代码) */
		xmlWriter.writeElementString("SubBrchId", "");/* 交易机构(银行机构代码) */
		xmlWriter.writeEndElement();
		xmlWriter.writeEndElement();
	}
	
	protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};

        // 消息报文头
        String macKey = getBankConfig().getValueAsString("macKey");
        WriteBankLogLn("通讯密钥内容:" + macKey);
        if (StringHelper.isNullOrEmpty(macKey)) {
        	tmpStrRet[0] = "E9981";
        	tmpStrRet[1] = "通讯密钥内容为空,请检查配置文件config.xml中'macKey'配置信息.";
        	return tmpStrRet;
        }
        
        String msgMac = Mac.generateMac(macKey.getBytes(getCharset()), p_reqStr.getBytes(getCharset()));
        byte[] msgMacBytes = msgMac.getBytes(getCharset());
        if (msgMacBytes.length != 16) {
        	tmpStrRet[0] = "E9981";
        	tmpStrRet[1] = "生成的MAC值:[" + msgMac + "]长度非16字节";
        	return tmpStrRet;
        }
        
        // 消息报文
        String tmpReqMsgHeader = String.format("%08d", msgMac + p_reqStr) + msgMac;
        String tmpReqData = tmpReqMsgHeader + p_reqStr;
        WriteBankLogStep2(tmpReqData);

        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + bankFront.serverPort + "]。");

        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqData.getBytes(getCharset()));
        tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(tmpStrRet[1]);
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }

        return tmpStrRet;
    }
	
	protected String[] sendToBank(String p_reqStr, String transPort) throws Exception {
        String[] tmpStrRet = new String[]{"", ""};

        // 消息报文头
        String macKey = getBankConfig().getValueAsString("macKey");
        WriteBankLogLn("通讯密钥内容:" + macKey);
        if (StringHelper.isNullOrEmpty(macKey)) {
        	tmpStrRet[0] = "E9981";
        	tmpStrRet[1] = "通讯密钥内容为空,请检查配置文件config.xml中'macKey'配置信息.";
        	return tmpStrRet;
        }
        
        String msgMac = Mac.generateMac(macKey.getBytes(getCharset()), p_reqStr.getBytes(getCharset()));
        byte[] msgMacBytes = msgMac.getBytes(getCharset());
        if (msgMacBytes.length != 16) {
        	tmpStrRet[0] = "E9981";
        	tmpStrRet[1] = "生成的MAC值:[" + msgMac + "]长度非16字节";
        	return tmpStrRet;
        }
        
        // 消息报文
        String tmpReqMsgHeader = String.format("%08d", msgMac + p_reqStr) + msgMac;
        String tmpReqData = tmpReqMsgHeader + p_reqStr;
        WriteBankLogStep2(tmpReqData);

        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(transPort), this);
        WriteBankLogLn("服务地址：[" + bankFront.serverIP + ":" + transPort + "]。");

        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpReqData.getBytes(getCharset()));
        tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(tmpStrRet[1]);
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }

        return tmpStrRet;
    }
	
	public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 24) {
                p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 0, 8, getCharset())) - 16;
                p_receiver.contentStartIndex = 24;
            }
        }
    }
}
